<template>
  <div class="col q-pa-sm q-validation-component">
    <q-table :data="data" :columns="columns" :pagination="pagination" class="cross_table col" color="primary" separator="cell" rowKey="id" :hide-bottom="true" style="min-height:150px;" :grid="imageUpload">
      <template v-slot:bottom-row>
        <q-tr v-if="errMsg">
          <q-td colspan="100%">
            <div class="text-red text-right q-mr-md">{{ errMsg }}</div>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:top>
        <div class="text-subtitle"><q-icon name="star" color="red" v-show="required" />{{ title }}</div>
        <q-space />
        <q-btn no-wrap :label="uploadBtnlabel" icon="mdi-cloud-upload-outline" :loading="importing" color="primary" @click="uploadFiles(data)" v-if="upload && !readonly">
          <q-tooltip v-if="!hint == ''">
            {{ hint }}
          </q-tooltip>
          <q-uploader :accept="uploadType" :max-files="fileNumber - data.length" auto-upload ref="fileUploader" :multiple="true" class="hidden" :url="uploadUrl" field-name="file" :form-fields="formFields" :headers="headers" :max-file-size="maxSize" @uploaded="uploadedFiles" @rejected="rejectedFiles" @added="addFile" />
        </q-btn>
      </template>
      <template v-slot:item="props">
        <div class="q-ma-xs">
          <q-img :src="imagePath(props.row.id)" style="height: 160px; width: 130px">
          </q-img>
          <div class="cc-pic-opt-btn rounded-borders">
            <q-btn flat round dense color="secondary" icon="mdi-image-search-outline" @click="viewImage(props.row)">
              <q-tooltip>查看图片</q-tooltip>
            </q-btn>
            <q-btn flat round dense color="primary" icon="mdi-cloud-download-outline" @click="downloadFile(props.row)" v-if="download">
              <q-tooltip>下载附件</q-tooltip>
            </q-btn>
            <btn-del v-if="del" label="附件" @confirm="delFile(props.row)" />
          </div>
        </div>
      </template>
      <template #body-cell-index="props">
        <q-td :props="props">{{ props.value }}</q-td>
      </template>
      <template #body-cell-name="props">
        <q-td :props="props">{{ props.value }}</q-td>
      </template>
      <template #body-cell-type="props">
        <q-td :props="props" width="100">{{ props.row.type }}</q-td>
      </template>
      <template #body-cell-createTime="props">
        <q-td :props="props" width="120">{{ props.row.createTime }}</q-td>
      </template>
      <template #body-cell-opt="props">
        <q-td :props="props" width="120">
          <q-btn v-if="checkIsImage(props.row)" flat round dense color="secondary" icon="mdi-image-search-outline" @click="viewImage(props.row)">
            <q-tooltip>查看图片</q-tooltip>
          </q-btn>
          <q-btn flat round dense color="primary" icon="mdi-cloud-download-outline" @click="downloadFile(props.row)" v-if="download">
            <q-tooltip>下载附件</q-tooltip>
          </q-btn>
          <btn-del v-if="del && !readonly" label="附件" @confirm="delFile(props.row)" />
        </q-td>
      </template>
    </q-table>
    <image-view ref="viewDialog" />
  </div>
</template>

<script>
import ImageView from 'components/imageview';

export default {
  name: 'InputUpload',
  components: { ImageView },
  props: {
    required: Boolean,
    title: {
      type: String,
      default: '标题',
    },
    uploadBtnlabel: {
      type: String,
      default: '上传附件',
    },
    fieldId: {
      type: [String, Number],
      default: '3',
    },
    dataId: {
      type: String,
      default: '2',
    },
    formId: {
      type: String,
      default: '1',
    },
    uploadType: {
      type: String,
    },
    fileNumber: {
      type: String,
    },
    imageUpload: {
      type: Boolean,
      default: false,
    },
    upload: {
      type: Boolean,
      required: false,
      default: true,
    },
    readonly: {
      type: Boolean,
      required: false,
      default: false,
    },
    download: {
      type: Boolean,
      required: false,
      default: true,
    },
    del: {
      type: Boolean,
      required: false,
      default: true,
    },
  },
  data() {
    return {
      maxSize: 50 * 1024 * 1024,
      fileLength: 0,
      formFields: [],
      importing: false,
      errMsg: '',
      hint: '',
      columns: [{
        name: 'name', label: '文件名称', field: 'name', align: 'center',
      }, {
        name: 'type', label: '文件类型', field: 'type', align: 'center',
      }, {
        name: 'createTime', label: '创建时间', field: 'createTime', align: 'center',
      },
      {
        name: 'opt', label: '操作', field: 'opt', align: 'center',
      }],
      data: [],
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/upload`,
      imgUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/dynView`,
      pagination: {
        page: 1,
        rowsPerPage: 100,
        rowsNumber: 99,
      },
      selectFile: {},
    };
  },
  watch: {
    data: {
      handler() {
        this.fileLength = this.data.length;
      },
    },
  },
  methods: {
    validate() {
      if (this.required && this.data.length === 0) {
        this.errMsg = '附件不能为空！';
        return false;
      }
      return true;
    },
    resetValidation() {
      this.errMsg = '';
    },
    rejectedFiles(rejectedEntries) {
      let fileLength = 0;
      rejectedEntries.forEach((rejectedFile) => {
        if (rejectedFile.failedPropValidation === 'max-file-size') {
          const { file } = rejectedFile;
          this.$error(`(${file.name})上传失败， 目前支持上传最大${this.maxSize / 1024 / 1024}MB`);
        }
        if (rejectedFile.failedPropValidation === 'max-files') {
          fileLength += 1;
        }
      });
      if (fileLength > 0) {
        this.$error(`有${fileLength}个附件上传失败， 总共最多允许上传${this.fileNumber}个附件！`);
      }
    },
    addFile(files) {

    },
    empty() {

    },
    imagePath(id) {
      let path = '';
      if (id) {
        if (id.startsWith('http')) {
          return id;
        }
        path = `${this.imgUrl}/${id}`;
      }
      return path;
    },
    query() {
      this.$axios.get(`/dyn/file/fileList?formId=${this.formId}&dataId=${this.dataId}&fieldId=${this.fieldId}`).then(({ result }) => {
        this.data = result;
      });
    },
    uploadFiles(data) {
      if (data.length >= this.fileNumber) {
        this.$error(`最多允许上传${this.fileNumber}个附件！`);
        return;
      }
      this.$refs.fileUploader.pickFiles();
      this.formFields = [
        { name: 'formId', value: this.formId },
        { name: 'dataId', value: this.dataId },
        { name: 'fieldId', value: this.fieldId }
      ];
    },
    uploadedFiles({ xhr }) {
      this.$refs.fileUploader.removeUploadedFiles();
      const { response } = xhr;
      const res = JSON.parse(response);
      if (res.code === 200) {
        this.query();
      } else {
        this.$error(res.message);
      }
    },
    closeView() {
      this.$refs.viewDialog.hide();
    },
    checkIsImage(row) {
      const fileName = row.name;
      if (fileName) {
        const extension = fileName.split('.').pop().toLowerCase();
        if (extension) {
          return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(extension);
        }
      }
      return false;
    },
    viewImage(row) {
      this.selectFile = row;
      this.$viewerApi({
        images: [this.imagePath(row.id)],
      });
    },
    downloadFile(row) {
      this.exporting = true;
      window.open(`${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/download?id=${row.id}`);
    },
    delFile({ id }) {
      this.$axios.delete(`/dyn/file/delete?id=${id}`).then((rs) => {
        this.$info(rs.message);
        this.query();
      });
    },
  },
  created() { },
  mounted() {
    if (this.uploadType === '') {
      this.hint = '';
    } else {
      this.hint = `仅支持上传${this.uploadType}格式的附件！`;
    }
    this.maxSize = process.env.MAX_FILE_SIZE;
    this.query();
  },
  computed: {
  },
};
</script>
<style lang="stylus"></style>
